package com.huisou.basedataservice;

import com.huisou.domain.InfoCategory;
import com.huisou.orm.HibernateDao;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class InfoCategoryDao extends HibernateDao<InfoCategory, Integer> {
	
	protected Logger				log	= LoggerFactory.getLogger(getClass());
	
	private final String			hql	= "select new InfoCategory(id ,name) from InfoCategory where parentId=?  order by orderNo asc ";	// and isDeleted=?
																																			
	@Resource
	RedisTemplate<String, List<InfoCategory>>	redisListTemplate;
	@Resource
	private StringRedisTemplate		stringRedisTemplate;
	
	/**
	 * 根据父类ID，获取新闻资讯类别
	 * 
	 * @param parentId
	 * @return
	 */
	public List<InfoCategory> getListByParentId(Integer parentId) {
		String key = RedisConstants.KEY_NEWS_CATES_PID + "_" + parentId;
		
		List<InfoCategory> listInfoCategory = null;
		try {
			listInfoCategory = redisListTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("读取资讯分类出错:" + e.getMessage());
		}
		if (listInfoCategory == null) {
			try {
				listInfoCategory = find(hql, parentId);
				redisListTemplate.opsForValue().set(key, listInfoCategory);
			}
			catch (DataAccessException e) {
				log.error("获取父类ID为{}的新闻资讯类别列表出错.", parentId);
			}
		}
		return listInfoCategory;
	}
	
	public String getNameByCode(String code) {
		String key = RedisConstants.KEY_NEWS_CATES_SIGNLE_NAME + "_" + code;
		
		String infoCategoryName = "";
		try {
			infoCategoryName = stringRedisTemplate.opsForValue().get(key);
		}
		catch (Exception e) {
			log.error("读取资讯分类出错:" + e.getMessage());
		}
		if (StringUtils.isBlank(infoCategoryName)) {
			try {
				infoCategoryName = findUniqueBy("code", code).getName();
				stringRedisTemplate.opsForValue().set(key, infoCategoryName);
			}
			catch (DataAccessException e) {
				log.error("获取新闻资讯类别列表出错.");
			}
		}
		return infoCategoryName;
	}
}
